package com.rzy.a_thread.a;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

/**
 * @author gaopeng
 * @time 2021/04/01 11:29:28
 */
public class App {
    public static void main(String[] args) throws IOException {

        Thread th = new Thread(() -> {
            System.out.println(Thread.currentThread() + "开始");
            try {
                Thread.sleep(3000);
            } catch(Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread() + "结束");
        });

        th.start();

        try {
            Thread.sleep(1000);
        } catch(Exception e) {
            e.printStackTrace();
        }

        System.out.println("=======================main====================");
        // 获取线程id
        long id = th.getId();

        // 根据线程id获取线程
        ThreadMXBean tmx = ManagementFactory.getThreadMXBean();
        ThreadInfo info = tmx.getThreadInfo(id);
        // 获取线程状态
        System.out.println(info.getThreadState());

        // 也可以直接通过th.getState()来获取线程的状态
        // 这是之所以使用线程id来获取线程，是为了证明另外一件事：我们可以通过线程id获得线程。
    }
}
